<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import {
  Button,
  Card,
  Col,
  DatePicker,
  Progress,
  Row,
  Table,
  Tabs,
  Tag,
} from 'ant-design-vue';
import dayjs from 'dayjs';

import StatisticsCard from '#/components/hotel/StatisticsCard.vue';

// 响应式数据
const dateRange = ref([dayjs().subtract(30, 'day'), dayjs()]);
const activeTab = ref('rent');

// KPI数据
const kpiData = ref({
  totalRooms: 50,
  occupancyRate: 85.6,
  monthlyRevenue: 125_000,
  avgRentCycle: 12.5,
  vacancyRate: 14.4,
});

// 房态统计数据
const roomStatusData = ref([
  {
    type: 'occupied',
    label: '已出租',
    count: 43,
    percentage: 86,
    icon: 'ant-design:home-filled',
    class: 'status-occupied',
  },
  {
    type: 'vacant',
    label: '空置',
    count: 5,
    percentage: 10,
    icon: 'ant-design:home-outlined',
    class: 'status-vacant',
  },
  {
    type: 'maintenance',
    label: '维护中',
    count: 2,
    percentage: 4,
    icon: 'ant-design:tool-outlined',
    class: 'status-maintenance',
  },
]);

// 收入趋势数据
const revenueData = ref([
  { month: '1月', value: 115_000 },
  { month: '2月', value: 120_000 },
  { month: '3月', value: 118_000 },
  { month: '4月', value: 125_000 },
  { month: '5月', value: 130_000 },
  { month: '6月', value: 128_000 },
]);

const maxRevenue = computed(() => {
  return Math.max(...revenueData.value.map((item) => item.value));
});

// 房型统计表格
const roomTypeColumns = [
  { title: '房型', dataIndex: 'type', key: 'type' },
  { title: '房间数', dataIndex: 'count', key: 'count' },
  { title: '出租率', dataIndex: 'occupancyRate', key: 'occupancyRate' },
  { title: '平均租金', dataIndex: 'avgRent', key: 'avgRent' },
];

const roomTypeData = ref([
  { type: '一室一厅', count: 20, occupancyRate: 90, avgRent: 2800 },
  { type: '两室一厅', count: 15, occupancyRate: 87, avgRent: 3800 },
  { type: '三室两厅', count: 10, occupancyRate: 80, avgRent: 4800 },
  { type: '豪华套房', count: 5, occupancyRate: 100, avgRent: 6800 },
]);

// 维修统计表格
const maintenanceColumns = [
  { title: '维修类型', dataIndex: 'type', key: 'type' },
  { title: '报修次数', dataIndex: 'count', key: 'count' },
  { title: '维修成本', dataIndex: 'cost', key: 'cost' },
  { title: '平均处理时间', dataIndex: 'avgProcessTime', key: 'avgProcessTime' },
];

const maintenanceData = ref([
  { type: '水电维修', count: 15, cost: 8500, avgProcessTime: 4.2 },
  { type: '电器维修', count: 8, cost: 6200, avgProcessTime: 3.8 },
  { type: '家具维修', count: 12, cost: 3200, avgProcessTime: 2.5 },
  { type: '设备维修', count: 6, cost: 4500, avgProcessTime: 5.1 },
]);

// 租金收入表格
const rentIncomeColumns = [
  { title: '房间号', dataIndex: 'roomNumber', key: 'roomNumber' },
  { title: '租客姓名', dataIndex: 'tenantName', key: 'tenantName' },
  { title: '租金金额', dataIndex: 'amount', key: 'amount' },
  { title: '支付状态', dataIndex: 'status', key: 'status' },
  { title: '支付日期', dataIndex: 'paymentDate', key: 'paymentDate' },
];

const rentIncomeData = ref([
  {
    roomNumber: '101',
    tenantName: '张三',
    amount: 3000,
    status: 'paid',
    paymentDate: '2024-01-15',
  },
  {
    roomNumber: '201',
    tenantName: '李四',
    amount: 4500,
    status: 'paid',
    paymentDate: '2024-01-16',
  },
  {
    roomNumber: '301',
    tenantName: '王五',
    amount: 6000,
    status: 'pending',
    paymentDate: '2024-01-17',
  },
]);

const rentIncomePagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 押金管理表格
const depositColumns = [
  { title: '房间号', dataIndex: 'roomNumber', key: 'roomNumber' },
  { title: '租客姓名', dataIndex: 'tenantName', key: 'tenantName' },
  { title: '押金金额', dataIndex: 'amount', key: 'amount' },
  { title: '押金状态', dataIndex: 'status', key: 'status' },
  { title: '收取日期', dataIndex: 'collectDate', key: 'collectDate' },
];

const depositData = ref([
  {
    roomNumber: '101',
    tenantName: '张三',
    amount: 6000,
    status: 'collected',
    collectDate: '2024-01-01',
  },
  {
    roomNumber: '201',
    tenantName: '李四',
    amount: 9000,
    status: 'collected',
    collectDate: '2024-01-02',
  },
  {
    roomNumber: '301',
    tenantName: '王五',
    amount: 12_000,
    status: 'refunded',
    collectDate: '2023-12-01',
  },
]);

const depositPagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 其他收费表格
const otherIncomeColumns = [
  { title: '收费项目', dataIndex: 'item', key: 'item' },
  { title: '房间号', dataIndex: 'roomNumber', key: 'roomNumber' },
  { title: '金额', dataIndex: 'amount', key: 'amount' },
  { title: '收费日期', dataIndex: 'chargeDate', key: 'chargeDate' },
];

const otherIncomeData = ref([
  {
    item: '清洁费',
    roomNumber: '101',
    amount: 200,
    chargeDate: '2024-01-15',
  },
  {
    item: '维修费',
    roomNumber: '201',
    amount: 500,
    chargeDate: '2024-01-16',
  },
  {
    item: '滞纳金',
    roomNumber: '301',
    amount: 100,
    chargeDate: '2024-01-17',
  },
]);

const otherIncomePagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 工具函数
const getProgressColor = (percent: number) => {
  if (percent >= 80) return '#52c41a';
  if (percent >= 60) return '#faad14';
  return '#ff4d4f';
};

const getPaymentStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    paid: 'success',
    pending: 'warning',
    overdue: 'error',
  };
  return colorMap[status] || 'default';
};

const getPaymentStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    paid: '已支付',
    pending: '待支付',
    overdue: '逾期',
  };
  return statusMap[status] || status;
};

const getDepositStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    collected: 'success',
    refunded: 'default',
    pending: 'warning',
  };
  return colorMap[status] || 'default';
};

const getDepositStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    collected: '已收取',
    refunded: '已退还',
    pending: '待处理',
  };
  return statusMap[status] || status;
};

// 事件处理函数
const handleDateRangeChange = (dates: any) => {
  console.log('日期范围变化:', dates);
  // 这里可以根据日期范围重新加载数据
};

const refreshData = () => {
  console.log('刷新数据');
  // 这里可以重新加载所有统计数据
};

// 初始化
onMounted(() => {
  console.log('数据分析页面已加载');
});
</script>

<template>
  <div class="analytics-page">
    <div class="page-header">
      <h2>数据与分析</h2>
      <div class="header-actions">
        <DatePicker.RangePicker
          v-model:value="dateRange"
          @change="handleDateRangeChange"
        />
        <Button type="primary" @click="refreshData">
          <IconifyIcon icon="ant-design:reload-outlined" />
          刷新数据
        </Button>
      </div>
    </div>

    <!-- 关键指标卡片 -->
    <Row :gutter="16" class="kpi-row">
      <Col :span="6">
        <StatisticsCard
          title="总房间数"
          :value="kpiData.totalRooms"
          color="#1890ff"
          icon="ant-design:home-outlined"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="出租率"
          :value="kpiData.occupancyRate"
          suffix="%"
          color="#52c41a"
          icon="ant-design:percentage-outlined"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="月收入"
          :value="kpiData.monthlyRevenue"
          prefix="¥"
          color="#faad14"
          icon="ant-design:dollar-outlined"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="平均出租周期"
          :value="kpiData.avgRentCycle"
          suffix="天"
          color="#722ed1"
          icon="ant-design:clock-circle-outlined"
        />
      </Col>
    </Row>

    <!-- 图表区域 -->
    <Row :gutter="16" class="charts-row">
      <!-- 房态统计 -->
      <Col :span="12">
        <Card title="房态统计" :bordered="false" class="chart-card">
          <div class="chart-container">
            <div class="room-status-grid">
              <div
                v-for="status in roomStatusData"
                :key="status.type"
                class="status-item"
                :class="status.class"
              >
                <div class="status-icon">
                  <IconifyIcon :icon="status.icon" />
                </div>
                <div class="status-info">
                  <div class="status-count">{{ status.count }}</div>
                  <div class="status-label">{{ status.label }}</div>
                  <div class="status-percentage">{{ status.percentage }}%</div>
                </div>
              </div>
            </div>
            <div class="chart-summary">
              <div class="summary-item">
                <span class="summary-label">空置率：</span>
                <span class="summary-value">{{ kpiData.vacancyRate }}%</span>
              </div>
              <div class="summary-item">
                <span class="summary-label">出租率：</span>
                <span class="summary-value">{{ kpiData.occupancyRate }}%</span>
              </div>
            </div>
          </div>
        </Card>
      </Col>

      <!-- 收入趋势 -->
      <Col :span="12">
        <Card title="收入趋势" :bordered="false" class="chart-card">
          <div class="chart-container">
            <div class="revenue-chart">
              <div
                v-for="(item, index) in revenueData"
                :key="index"
                class="revenue-bar"
              >
                <div class="bar-container">
                  <div
                    class="bar-fill"
                    :style="{ height: `${(item.value / maxRevenue) * 100}%` }"
                  ></div>
                </div>
                <div class="bar-label">{{ item.month }}</div>
                <div class="bar-value">¥{{ item.value.toLocaleString() }}</div>
              </div>
            </div>
          </div>
        </Card>
      </Col>
    </Row>

    <!-- 详细统计表格 -->
    <Row :gutter="16" class="tables-row">
      <!-- 房型统计 -->
      <Col :span="12">
        <Card title="房型统计" :bordered="false" class="table-card">
          <Table
            :columns="roomTypeColumns"
            :data-source="roomTypeData"
            :pagination="false"
            size="small"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'occupancyRate'">
                <Progress
                  :percent="record.occupancyRate"
                  :stroke-color="getProgressColor(record.occupancyRate)"
                  size="small"
                />
              </template>
              <template v-else-if="column.key === 'avgRent'">
                ¥{{ record.avgRent.toLocaleString() }}
              </template>
            </template>
          </Table>
        </Card>
      </Col>

      <!-- 维修统计 -->
      <Col :span="12">
        <Card title="维修统计" :bordered="false" class="table-card">
          <Table
            :columns="maintenanceColumns"
            :data-source="maintenanceData"
            :pagination="false"
            size="small"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'cost'">
                ¥{{ record.cost.toLocaleString() }}
              </template>
              <template v-else-if="column.key === 'avgProcessTime'">
                {{ record.avgProcessTime }}小时
              </template>
            </template>
          </Table>
        </Card>
      </Col>
    </Row>

    <!-- 收入明细 -->
    <Card title="收入明细" :bordered="false" class="detail-card">
      <Tabs v-model:active-key="activeTab">
        <Tabs.TabPane key="rent" tab="租金收入">
          <Table
            :columns="rentIncomeColumns"
            :data-source="rentIncomeData"
            :pagination="rentIncomePagination"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'amount'">
                ¥{{ record.amount.toLocaleString() }}
              </template>
              <template v-else-if="column.key === 'status'">
                <Tag :color="getPaymentStatusColor(record.status)">
                  {{ getPaymentStatusText(record.status) }}
                </Tag>
              </template>
            </template>
          </Table>
        </Tabs.TabPane>
        <Tabs.TabPane key="deposit" tab="押金管理">
          <Table
            :columns="depositColumns"
            :data-source="depositData"
            :pagination="depositPagination"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'amount'">
                ¥{{ record.amount.toLocaleString() }}
              </template>
              <template v-else-if="column.key === 'status'">
                <Tag :color="getDepositStatusColor(record.status)">
                  {{ getDepositStatusText(record.status) }}
                </Tag>
              </template>
            </template>
          </Table>
        </Tabs.TabPane>
        <Tabs.TabPane key="other" tab="其他收费">
          <Table
            :columns="otherIncomeColumns"
            :data-source="otherIncomeData"
            :pagination="otherIncomePagination"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'amount'">
                ¥{{ record.amount.toLocaleString() }}
              </template>
            </template>
          </Table>
        </Tabs.TabPane>
      </Tabs>
    </Card>
  </div>
</template>

<style scoped>
.analytics-page {
  padding: 16px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.kpi-row {
  margin-bottom: 24px;
}

.charts-row {
  margin-bottom: 24px;
}

.chart-card {
  height: 400px;
}

.chart-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.room-status-grid {
  display: grid;
  flex: 1;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  margin-bottom: 24px;
}

.status-item {
  display: flex;
  align-items: center;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.status-item:hover {
  box-shadow: 0 4px 12px rgb(0 0 0 / 10%);
  transform: translateY(-2px);
}

.status-item.status-occupied {
  color: white;
  background: linear-gradient(135deg, #52c41a, #73d13d);
}

.status-item.status-vacant {
  color: white;
  background: linear-gradient(135deg, #ff4d4f, #ff7875);
}

.status-item.status-maintenance {
  color: white;
  background: linear-gradient(135deg, #faad14, #ffc53d);
}

.status-icon {
  margin-right: 12px;
  font-size: 24px;
}

.status-info {
  flex: 1;
}

.status-count {
  margin-bottom: 4px;
  font-size: 24px;
  font-weight: bold;
}

.status-label {
  margin-bottom: 2px;
  font-size: 14px;
}

.status-percentage {
  font-size: 12px;
  opacity: 0.8;
}

.chart-summary {
  display: flex;
  justify-content: space-around;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.summary-item {
  text-align: center;
}

.summary-label {
  font-size: 14px;
  color: #666;
}

.summary-value {
  margin-left: 8px;
  font-size: 18px;
  font-weight: bold;
  color: #1890ff;
}

.revenue-chart {
  display: flex;
  align-items: end;
  justify-content: space-around;
  height: 100%;
  padding: 20px 0;
}

.revenue-bar {
  display: flex;
  flex: 1;
  flex-direction: column;
  align-items: center;
  max-width: 80px;
}

.bar-container {
  position: relative;
  width: 40px;
  height: 200px;
  margin-bottom: 8px;
  overflow: hidden;
  background: #f0f0f0;
  border-radius: 4px;
}

.bar-fill {
  position: absolute;
  bottom: 0;
  width: 100%;
  background: linear-gradient(to top, #1890ff, #40a9ff);
  transition: height 0.3s ease;
}

.bar-label {
  margin-bottom: 4px;
  font-size: 12px;
  color: #666;
}

.bar-value {
  font-size: 12px;
  font-weight: 500;
  color: #1890ff;
}

.tables-row {
  margin-bottom: 24px;
}

.table-card {
  height: 400px;
}

.detail-card {
  margin-bottom: 24px;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 600;
  background-color: #fafafa;
}

:deep(.ant-progress-text) {
  font-size: 12px;
}
</style>
